package com.ruoyi.teaching.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.uuid.Seq;
import com.ruoyi.li.work.mapper.SysDeptMapper;
import com.ruoyi.li.work.mapper.SysUserMapper;
import com.ruoyi.li.work.mapper.SysUserRoleMapper;
import com.ruoyi.teaching.domain.*;
import com.ruoyi.teaching.domain.vo.PlatformQQuestionVO;
import com.ruoyi.teaching.domain.vo.PlatformUVirtualVO;
import com.ruoyi.teaching.mapper.*;
import com.ruoyi.teaching.service.PlatformUVirtualService;
import com.ruoyi.teaching.utils.UniversalUtil;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

import static com.ruoyi.common.utils.file.FileUploadUtils.getAbsoluteFile;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 王旭
 * @since 2024-06-29
 */
@Service
public class PlatformUVirtualServiceImpl extends ServiceImpl<PlatformUVirtualMapper, PlatformUVirtual> implements PlatformUVirtualService {

    private static final String VIRTUAL_VIEWS_KEY_PREFIX = "virtual:views:";

    @Autowired
    private PlatformUVirtualMapper platformUVirtualMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private PlatformSCollectMapper platformSCollectMapper;

    @Autowired
    private PlatformLLearnMapper platformLLearnMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private PlatformCSpecialtyMapper specialtyMapper;

    @Autowired
    private PlatformUVirtualLearnTimeMapper virtualLearnTimeMapper;

    private static final Map<Integer, String> QUESTION_TYPE_MAP = new HashMap<>();

    static {
        QUESTION_TYPE_MAP.put(0, "单选题");
        QUESTION_TYPE_MAP.put(1, "多选题");
        QUESTION_TYPE_MAP.put(2, "判断题");
    }

    /**
     * 查询用户自己的虚拟仿真列表
     */
    @Override
    public AjaxResult selectPlatformUVirtualListOwn(Integer pageNum, Integer pageSize, Integer virtualType, Integer vettingStatus, String virtualName) {
        // 创建查询条件构造器
        QueryWrapper<PlatformUVirtual> wrapper = new QueryWrapper<>();

        // 创建分页对象
        Page<PlatformUVirtual> page = new Page<>(pageNum, pageSize);

        // 获取当前用户的 ID
        int userId = SecurityUtils.getUserId().intValue();
        wrapper.eq("create_id", userId);

        // 添加查询条件：虚拟类型
        if (virtualType != null) {
            wrapper.apply("find_in_set({0}, virtual_type)", virtualType);
        }

        // 添加查询条件：审核状态
        if (vettingStatus != null) {
            wrapper.eq("vetting_status", vettingStatus);
        }

        // 添加查询条件：虚拟名称
        if (virtualName != null && !virtualName.isEmpty()) {
            wrapper.like("virtual_name", virtualName);
        }

        // 按照 ID 降序排序
        wrapper.orderByDesc("id");

        // 执行分页查询
        Page<PlatformUVirtual> page1 = platformUVirtualMapper.selectPage(page, wrapper);

        // 转换查询结果
        List<PlatformUVirtualVO> platformUVirtualVOS = new ArrayList<>();
        for (PlatformUVirtual record : page1.getRecords()) {
            PlatformUVirtualVO platformUVirtualVO = convertToVO(record);
            platformUVirtualVOS.add(platformUVirtualVO);
        }

        // 设置分页结果
        Page<PlatformUVirtualVO> platformUVirtualVOPage = new Page<>(pageNum, pageSize);
        BeanUtils.copyProperties(page1, platformUVirtualVOPage);
        platformUVirtualVOPage.setRecords(platformUVirtualVOS);

        // 返回结果
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", platformUVirtualVOPage);
    }

    /**
     * 将 PlatformUVirtual 实体转换为 PlatformUVirtualVO
     */
    private PlatformUVirtualVO convertToVO(PlatformUVirtual record) {
        PlatformUVirtualVO platformUVirtualVO = new PlatformUVirtualVO();
        BeanUtils.copyProperties(record, platformUVirtualVO);

        // 转换虚拟类型
        String virtualType = record.getVirtualType();
        Integer[] virtualTypeArray = UniversalUtil.stringToArray(virtualType, Integer::valueOf, Integer.class);
        platformUVirtualVO.setVirtualType(virtualTypeArray);

        // 转换专业ID
        String professionalId = record.getProfessionalId();
        Integer[] professionalIdArray = UniversalUtil.stringToArray(professionalId, Integer::valueOf, Integer.class);
        List<String> professionalName = new ArrayList<>();
        for (Integer integer : professionalIdArray) {
            PlatformCSpecialty platformCSpecialty = specialtyMapper.selectById(integer);
            professionalName.add(platformCSpecialty.getSpecialtyName());
        }
        platformUVirtualVO.setProfessionalId(professionalIdArray);
        platformUVirtualVO.setProfessionalName(professionalName);

        //查找大类id
        Integer professionalCategoryId = record.getProfessionalCategoryId();
        PlatformCSpecialty platformCSpecialty = specialtyMapper.selectById(professionalCategoryId);
        platformUVirtualVO.setProfessionalCategoryName(platformCSpecialty.getSpecialtyName());

        // 转换标签ID
        String softwareTag = record.getSoftwareTag();
        Long[] softwareTagIds = UniversalUtil.stringToArray(softwareTag, Long::valueOf, Long.class);
        platformUVirtualVO.setSoftwareTag(softwareTagIds);


        // 添加学习人数
        QueryWrapper<PlatformLLearn> platformLLearnQueryWrapper = new QueryWrapper<>();
        platformLLearnQueryWrapper.eq("project_id", platformUVirtualVO.getId()).eq("learn_type", 0);
        List<PlatformLLearn> newList = new ArrayList<>();
        List<PlatformLLearn> platformLLearns = platformLLearnMapper.selectList(platformLLearnQueryWrapper);
        platformLLearns.stream().filter(UniversalUtil.distinctByKey(PlatformLLearn::getLearnPersonId)) // filter保留true的值
                .forEach(newList::add);
        platformUVirtualVO.setLearnNumber(newList.size());

        // 如果有题库的话将题目由字符串转成对象
        if (StringUtils.isNotEmpty(record.getQuestionUrl())) {
            String questionInfo = record.getQuestionInfo();
            List<PlatformQQuestionVO> platformQQuestionVOS = JSON.parseArray(questionInfo, PlatformQQuestionVO.class);
            platformUVirtualVO.setPlatformQQuestionDTOs(platformQQuestionVOS);
        }

        //添加学习时长
        QueryWrapper<PlatformUVirtualLearnTime> virtualLearnTimeQueryWrapper = new QueryWrapper<>();
        virtualLearnTimeQueryWrapper.in("pid", record.getId());
        List<PlatformUVirtualLearnTime> virtualLearnTimeList = virtualLearnTimeMapper.selectList(virtualLearnTimeQueryWrapper);
        if(!CollectionUtils.isEmpty(virtualLearnTimeList)){
            BigDecimal totalLearnTimeInMinutes = calculateTotalLearnTime(virtualLearnTimeList, "m");
            platformUVirtualVO.setStudyTime(String.valueOf(totalLearnTimeInMinutes.divide(BigDecimal.valueOf(virtualLearnTimeList.size()), 1, RoundingMode.HALF_UP)));
        }else {
            platformUVirtualVO.setStudyTime("0");
        }


        //添加浏览量
        String viewKey = VIRTUAL_VIEWS_KEY_PREFIX + record.getId();
        Object views = redisCache.getCacheMapValue(viewKey, "views");
        if (views != null) {
            int viewCount = Integer.parseInt(views.toString());
            platformUVirtualVO.setLookNum(viewCount);
        }else {
            platformUVirtualVO.setLookNum(0);
        }

        // 判断该虚拟仿真是否被收藏
        // 获取用户ID，如果无法获取则捕获异常
        Integer userId = null;
        try {
            userId = SecurityUtils.getUserId().intValue();
        } catch (ServiceException e) {
            platformUVirtualVO.setCollect(0);
            return platformUVirtualVO;
        }
        QueryWrapper<PlatformSCollect> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("person_id", userId).eq("collect_type", 0).eq("project_id", platformUVirtualVO.getId());
        int collectCount = Math.toIntExact(platformSCollectMapper.selectCount(queryWrapper));
        platformUVirtualVO.setCollect(collectCount > 0 ? 1 : 0);

        return platformUVirtualVO;
    }

    /**
     * 根据ID查询虚拟仿真
     */
    @Override
    public AjaxResult selectPlatformUVirtualById(Long id) {
        PlatformUVirtual platformUVirtual = platformUVirtualMapper.selectById(id);
        if (null == platformUVirtual) {
            return new AjaxResult(HttpStatus.SUCCESS, "该虚拟仿真不存在");
        }
        PlatformUVirtualVO platformUVirtualVO = convertToVO(platformUVirtual);
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", platformUVirtualVO);
    }

    /**
     * 系统管理员查询虚拟仿真列表
     */
    @Override
    public AjaxResult selectPlatformUVirtualListSystemAdmin(Integer pageNum, Integer pageSize, Integer virtualType, Integer vettingStatus, String virtualName) {
        // 创建查询条件构造器
        QueryWrapper<PlatformUVirtual> wrapper = new QueryWrapper<>();

        // 创建分页对象
        Page<PlatformUVirtual> page = new Page<>(pageNum, pageSize);

        // 添加查询条件：虚拟名称
        if (virtualName != null && !virtualName.isEmpty()) {
            wrapper.like("virtual_name", virtualName);
        }

        // 添加查询条件：审核状态
        if (vettingStatus != null) {
            wrapper.eq("vetting_status", vettingStatus);
        }

        // 添加查询条件：虚拟类型
        if (virtualType != null) {
            wrapper.apply("find_in_set({0}, virtual_type)", virtualType);
        }

        // 按照 ID 降序排序
        wrapper.orderByDesc("id");

        // 执行分页查询
        Page<PlatformUVirtual> page1 = platformUVirtualMapper.selectPage(page, wrapper);

        // 转换查询结果
        List<PlatformUVirtualVO> platformUVirtualVOS = new ArrayList<>();
        for (PlatformUVirtual record : page1.getRecords()) {
            PlatformUVirtualVO platformUVirtualVO = convertToVO(record);
            platformUVirtualVOS.add(platformUVirtualVO);
        }

        // 设置分页结果
        Page<PlatformUVirtualVO> platformUVirtualVOPage = new Page<>(pageNum, pageSize);
        BeanUtils.copyProperties(page1, platformUVirtualVOPage);
        platformUVirtualVOPage.setRecords(platformUVirtualVOS);

        // 返回结果
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", platformUVirtualVOPage);
    }

    /**
     * @param pageNum                页码
     * @param pageSize               条数
     * @param virtualType            软件类型（0PC,1VR,2MR,3AR）
     * @param professionalCategoryId 专业大类
     * @param professionalId         专业分类
     * @param virtualName            虚拟仿真名称
     * @param sortord                排序方式（0默认先按评分再按上传时间，1评分）
     * @return
     */
    @Override
    public AjaxResult selectPlatformUVirtualListUser(Integer pageNum, Integer pageSize, Integer virtualType, Integer professionalCategoryId, Integer professionalId, String virtualName, Integer sortord, Long softwareTagId) {
        Page<PlatformUVirtual> platformUVirtualPage = new Page<>(pageNum, pageSize);
        QueryWrapper<PlatformUVirtual> wrapper = new QueryWrapper<>();
        wrapper.eq("vetting_status", 1);
        if (null != virtualType && virtualType != 999) {
            wrapper.apply("find_in_set({0}, virtual_type)", virtualType);
        }
        if (null != professionalCategoryId && professionalCategoryId != 999) {
            wrapper.eq("professional_category_id", professionalCategoryId);
        }
        if (null != professionalId && professionalId != 999) {
            wrapper.apply("find_in_set({0}, professional_id)", professionalId);
        }
        if (null != virtualName && !virtualName.equals("")) {
            wrapper.like("virtual_name", virtualName);
            // 记录搜索词，类型为"0虚拟仿真"
            redisCache.recordSearchTerm(0, virtualName);
        }
        if (null != softwareTagId && softwareTagId != 999) {
            wrapper.apply("find_in_set({0}, software_tag)", softwareTagId);
        }
        // 排序
        if (sortord != null && sortord == 1) {
            // 按评分排序
            wrapper.orderByDesc("grade");
        } else {
            // 默认排序，先按评分再按上传时间排序
            wrapper.orderByDesc("grade", "create_time");
        }
        platformUVirtualPage = platformUVirtualMapper.selectPage(platformUVirtualPage, wrapper);

        // 转换查询结果
        List<PlatformUVirtualVO> platformUVirtualVOS = new ArrayList<>();
        for (PlatformUVirtual record : platformUVirtualPage.getRecords()) {
            PlatformUVirtualVO platformUVirtualVO = convertToVO(record);
            platformUVirtualVOS.add(platformUVirtualVO);
        }

        // 设置分页结果
        Page<PlatformUVirtualVO> platformUVirtualVOPage = new Page<>(pageNum, pageSize);
        BeanUtils.copyProperties(platformUVirtualPage, platformUVirtualVOPage);
        platformUVirtualVOPage.setRecords(platformUVirtualVOS);

        // 返回结果
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", platformUVirtualVOPage);
    }

    @Override
    public AjaxResult selectHotSearch() {
        Set<Object> top5SearchTerms = redisCache.getTop5SearchTerms(0);
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", top5SearchTerms);
    }

    /**
     * 上传虚拟仿真题库
     */
    @Override
    public AjaxResult insertPlatformUVirtualQuestions(List<PlatformQQuestionVO> questions, String urlBefore) throws IOException {
        // 创建一个新的工作簿
        Workbook workbook = new XSSFWorkbook();
        // 创建一个新的工作表
        Sheet sheet = workbook.createSheet("Questions");

        // 创建表头行，并设置表头名称
        String[] headers = {"题目类型", "题目名称", "正确答案", "选项A", "选项B", "选项C", "选项D", "选项E", "选项F"};
        Row headerRow = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }

        // 填充数据行
        int rowNum = 1;
        for (PlatformQQuestionVO question : questions) {
            Row row = sheet.createRow(rowNum++);

            // 设置题目类型（使用汉字）
            String questionType = QUESTION_TYPE_MAP.get(question.getQuestionType());
            row.createCell(0).setCellValue(questionType != null ? questionType : "");

            // 设置题目名称
            row.createCell(1).setCellValue(question.getQuestionName());

            // 设置答案
            if (question.getQuestionType() == 1) { // 多选题
                StringJoiner answers = new StringJoiner(",");
                for (String answer : question.getQuestionAnswerMore()) {
                    answers.add(answer);
                }
                row.createCell(2).setCellValue(answers.toString());
            } else { // 单选题或其他类型
                row.createCell(2).setCellValue(question.getQuestionAnswer());
            }

            // 设置选项
            List<Option> options = question.getOptions();
            for (int i = 0; i < options.size(); i++) {
                row.createCell(3 + i).setCellValue(options.get(i).getContent());
            }
        }

        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        String fileName = StringUtils.format("{}/{}_{}.{}",
                DateUtils.datePath(),  // 生成日期路径
                FilenameUtils.getBaseName("虚拟仿真题库"),  // 获取文件基础名称（不包括扩展名）
                Seq.getId(Seq.uploadSeqType),  // 获取唯一序列ID
                "xlsx");  // 获取文件扩展名

        // 获取文件绝对路径
        String absPath = getAbsoluteFile(filePath, fileName).getAbsolutePath();
        int dirLastIndex = RuoYiConfig.getProfile().length() + 1;
        String currentDir = StringUtils.substring(filePath, dirLastIndex);
        String reallyFileName = Constants.RESOURCE_PREFIX + "/" + currentDir + "/" + fileName;
        String url = urlBefore + reallyFileName;

        // 尝试写入文件
        try (FileOutputStream fileOut = new FileOutputStream(absPath)) {
            workbook.write(fileOut);
            workbook.close();

            // 检查文件是否存在
            File file = new File(absPath);
            boolean exists = file.exists();
            if (exists) {
                return new AjaxResult(HttpStatus.SUCCESS, "题库上传成功", url);
            }
            return new AjaxResult(HttpStatus.ERROR, "题库上传失败，请联系管理员");
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(HttpStatus.ERROR, "题库上传失败，请联系管理员");
        }
    }

    @Override
    public void addView(Long id) {
        String viewKey = VIRTUAL_VIEWS_KEY_PREFIX + id;
        redisCache.getIncrementValue(viewKey, "views", 1);
    }


    /**
     * 添加虚拟仿真
     */
    @Override
    public AjaxResult insertPlatformUVirtual(PlatformUVirtualVO platformUVirtualVO) {
        PlatformUVirtual platformUVirtual = new PlatformUVirtual();
        BeanUtils.copyProperties(platformUVirtualVO, platformUVirtual);

        // 拼接虚拟类型，专业ID和标签
        platformUVirtual.setVirtualType(joinArray(platformUVirtualVO.getVirtualType()));
        platformUVirtual.setProfessionalId(joinArray(platformUVirtualVO.getProfessionalId()));
        platformUVirtual.setSoftwareTag(joinArray(platformUVirtualVO.getSoftwareTag()));


        // 设置创建信息
        UniversalCreateUpdate create = UniversalUtil.getCreateUpdate(sysUserMapper);
        platformUVirtual.setCreateBy(create.getName());
        platformUVirtual.setCreateTime(DateUtils.getNowDate());
        platformUVirtual.setCreateId(create.getId());

        // 如果有execl转化题目数据
        if (StringUtils.isNotBlank(platformUVirtualVO.getQuestionUrl())) {
            List<PlatformQQuestionVO> platformQQuestionDTOs = platformUVirtualVO.getPlatformQQuestionDTOs();
            String jsonString = com.alibaba.fastjson2.JSON.toJSONString(platformQQuestionDTOs);
            platformUVirtual.setQuestionInfo(jsonString);
        } else {
            platformUVirtual.setQuestionInfo(null);
        }

        // 设置上传人所属学校
        String topLevelSchoolName = UniversalUtil.findTopLevelSchoolName(sysUserRoleMapper, sysDeptMapper, sysUserMapper, null);
        if (!"".equals(topLevelSchoolName)) {
            platformUVirtual.setUploadPersonSchool(topLevelSchoolName);
        }

        Long userId = null;
        try {
            userId = SecurityUtils.getUserId();
            // 未登录用户，按普通用户处理
        } catch (ServiceException e) {

        }
        int roleId = 0;
        if (userId != null) {
            roleId = Math.toIntExact(sysUserRoleMapper.selectRoleIdbyUserId(userId)[0]);
        }
        boolean roleSystemAdmin = (roleId == 1 || roleId == 6);// 超级管理员
        if (roleSystemAdmin) {
            platformUVirtual.setVettingStatus(1);
        } else {
            platformUVirtual.setVettingStatus(0);
        }

        // 插入数据
        int insert = platformUVirtualMapper.insert(platformUVirtual);
        if (insert > 0) {
            return new AjaxResult(HttpStatus.SUCCESS, "添加成功");
        } else {
            return new AjaxResult(HttpStatus.ERROR, "添加失败");
        }
    }

    /**
     * 更新虚拟仿真审核状态
     */
    @Override
    public AjaxResult updatePlatformUVirtualVetting(VettingRequest vettingRequest) {
        PlatformUVirtual platformUVirtual = new PlatformUVirtual();
        BeanUtils.copyProperties(vettingRequest, platformUVirtual);
        long l = vettingRequest.getId().longValue();
        platformUVirtual.setId(l);

        // 设置更新时间和更新人信息
        platformUVirtual.setUpdateTime(DateUtils.getNowDate());
        UniversalCreateUpdate update = UniversalUtil.getCreateUpdate(sysUserMapper);
        platformUVirtual.setUpdateBy(update.getName());
        platformUVirtual.setUpdateId(update.getId());

        // 更新数据
        int updateResult = platformUVirtualMapper.updateById(platformUVirtual);
        if (updateResult > 0) {
            return new AjaxResult(HttpStatus.SUCCESS, "审核成功");
        } else {
            return new AjaxResult(HttpStatus.ERROR, "审核失败，请联系管理员");
        }
    }

    /**
     * 批量删除虚拟仿真
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public AjaxResult deletePlatformUVirtualByIds(Long[] ids) {
        int expectedDeleteCount = ids.length;
        int actualDeleteCount = platformUVirtualMapper.deleteBatchIds(Arrays.asList(ids));
        if (expectedDeleteCount == actualDeleteCount) {
            // 删除收藏与虚拟仿真的关联
            deleteCollectAndVirtual(ids);
            // 删除学习记录与虚拟仿真的关联
            deleteLearnAndVirtual(ids);
            return new AjaxResult(HttpStatus.SUCCESS, "删除成功");
        } else {
            throw new RuntimeException("删除失败");
        }
    }

    private void deleteLearnAndVirtual(Long[] ids) {
        for (Long id : ids) {
            int projectId = id.intValue();
            QueryWrapper<PlatformLLearn> platformLLearnQueryWrapper = new QueryWrapper<>();
            platformLLearnQueryWrapper.eq("project_id", projectId);
            platformLLearnQueryWrapper.eq("learn_type", 0);
            platformLLearnMapper.delete(platformLLearnQueryWrapper);
        }
    }

    private void deleteCollectAndVirtual(Long[] ids) {
        for (Long id : ids) {
            int projectId = id.intValue();
            QueryWrapper<PlatformSCollect> platformSCollectQueryWrapper = new QueryWrapper<>();
            platformSCollectQueryWrapper.eq("collect_type", 0);
            platformSCollectQueryWrapper.eq("project_id", projectId);
            platformSCollectMapper.delete(platformSCollectQueryWrapper);
        }
    }

    /**
     * 将数组转换为逗号分隔的字符串
     *
     * @param array 输入数组
     * @param <T>   数组类型
     * @return 拼接后的字符串
     */
    private <T> String joinArray(T[] array) {
        if (array == null) {
            return "";
        }
        return Arrays.stream(array)
                .map(String::valueOf)
                .collect(Collectors.joining(","));
    }

    private BigDecimal calculateTotalLearnTime(List<PlatformUVirtualLearnTime> virtualLearnTimeList, String unit) {
        BigDecimal totalTime = BigDecimal.ZERO;  // 初始化总时间为0

        List<TimePeriod> timePeriods = new ArrayList<>();
        for (PlatformUVirtualLearnTime learnTime : virtualLearnTimeList) {
            // 获取每条记录的开始和结束时间
            Date startTime = learnTime.getStartTime();
            Date endTime = learnTime.getEndTime();

            if (startTime != null && endTime != null) {
                // 格式化时间为yyyy-MM-dd HH:mm:ss字符串
                String startStr = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(startTime);
                String endStr = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endTime);


                TimePeriod timePeriod = new TimePeriod();
                timePeriod.setStartTime(startStr);
                timePeriod.setEndTime(endStr);
                timePeriods.add(timePeriod);
            }
        }
        totalTime = UniversalUtil.calculateTotalTimeDifference(timePeriods, unit);

        // 返回总时长
        return totalTime;
    }

}
